package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.metagurukul.metagranth.service.UserService;
import com.metagurukul.metagranth.vo.User;

/**
 * Servlet implementation class ProfileServlet
 * This servlet is responsible for handling the profile information of each registered user
 * @author team MetaGranth
 *
 */
public class ProfileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProfileServlet() {
        super();
       
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPerform(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPerform(request,response);
	}

	/**
	 * this function will get the userName of user, creates the User object ,sets its userName ,
	 * gets the retrieved userInfo by calling getProfile in UserService service layer
	 * and if retrieved user is null, redirects it to profile.jsp,
	 * else to eror.jsp
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doPerform(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		if(session.getAttribute("userId")!=null){
		try{
			String userName=(String) request.getSession().getAttribute("userName");
			User user=new User();
			user.setUsername(userName);
			User retrievedUser = UserService.getProfile(user);
			RequestDispatcher rd = null;
			if(retrievedUser!=null) {
			request.setAttribute("userProfile",retrievedUser );
			rd=	request.getRequestDispatcher("profile.jsp");
			}
			else {
				request.setAttribute("errorMessage", "Oops Something Went Wrong!! :-( Try Again Later");
				rd = request.getRequestDispatcher("errorPage.jsp");
			}

			rd.forward(request, response);
			
		}catch(Exception exception) {
			request.setAttribute("errormsg", exception.getMessage());
			request.getRequestDispatcher("errorPage.jsp").forward(request, response);
		}
		} else {
			response.sendRedirect("index.jsp");
		}
	}
}
